import jwt

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from blog.settings import SECRET_KEY


class LoginAuthentication(BaseAuthentication):
    """登录认证类"""

    def authenticate(self, request):
        token = request.META.get('HTTP_TOKEN')
        if token:
            try:
                result = jwt.decode(token, SECRET_KEY, algorithm='HS256')
                userid = result['data']['userid']
                locked = result['data']['locked']
                if locked:
                    raise AuthenticationFailed('用户被禁言无法发布文章')
                userid2 = int(request.data.get('userid', '0'))
                if userid != userid2:
                    raise AuthenticationFailed('身份标识失效请重新登录')
                return userid, token
            except Exception:
                pass
        raise AuthenticationFailed('请提供有效的身份认证标识')
